package com.inspur.dgov.common.cloud.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;

/**
 * feign 传递Request header
 *
 * @Author chiyupei
 * @Date 19/6/26 下午8:51
 * @Version 1.0
 * @Description feign 传递Request header
 */
@Slf4j
public class FeignRequestHeaderInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs != null) {
            HttpServletRequest request = attrs.getRequest();
            // 租户信息
            String tenantCode = "";
            Collection<String> tenantC = requestTemplate.queries().get("tenantCode");
            if (null != tenantC) {
                List<String> tenantL = new ArrayList(tenantC);
                tenantCode = tenantL.get(0);
            }
            if (StringUtils.isNotBlank(tenantCode)) {
                requestTemplate.header("tenantCode", tenantCode);
            }
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String value = request.getHeader(name);
                    if ("dgov-auth".equals(name)) {
                        requestTemplate.header(name, value);
                    }
                }
            }
        }
    }
}
